const { Add, Update, QueryOne, Query, ExecGetOne } = require('../db/dbhelper');
var { init, format } = require('../models/persondes');
var _ = require('underscore');
const logger = require('../libs/log').logger;

//保存
const persondesSave = async function (doc) {
  try {
    logger.info(`----------------persondesSave--------doc:`,doc)
    if (!doc.pcode) {
      return {
        code: 1,
        msg: 'pcode参数不能为空'
      }
    }
    if (!doc.type) {
      return {
        code: 1,
        msg: 'type参数不能为空'
      }
    }
    let pl = await QueryOne('hzz_persondes', { pcode: doc.pcode, type: doc.type }, null);
    if (pl) {
      doc.id = pl.id;
      await Update('hzz_persondes', format(doc));
    } else {
      await Add('hzz_persondes', init(doc));
    }
    return {
      code: 0,
      msg: '保存信息成功'
    }
  } catch (error) {
    logger.info(`----------------persondesSave--------error:`,error)
    return {
      code: 1,
      msg: error ? error.message : '保存信息异常'
    }
  }
}
//查询详情
const persondesQueryOne = function (pcode) {
  return QueryOne('hzz_persondes', { pcode: pcode }, null);
}
//列表
const persondesList = function (doc) {
  return Query('hzz_persondes', doc);
}
// 导入描述信息保存
const persondesImport = async function (doc) {
  try {
    logger.info(`------persondesImport-----------doc:`,doc);
    let data;
    let pcode = doc.pcode;
    doc = _.omit(doc, 'pcode');
    for (const key in doc) {
      if (Object.hasOwnProperty.call(doc, key)) {
        const item = doc[key];
        data = await ExecGetOne(`select * from hzz_persondes where pcode='${pcode}' and type='${key}'`);
        if (data) {
          data.remarks = item;
          await Update('hzz_persondes', format(data));
        } else {
          let newObj = {
            pcode: pcode,
            type: key,
            remarks: item
          };
          await Add('hzz_persondes', init(newObj));
        }
      }
    }
  } catch (error) {
    logger.error(`------persondesImport-----------error:`,error);
  }
}

module.exports = {
  persondesSave,
  persondesQueryOne,
  persondesList,
  persondesImport
}